package com.company.eduorder.exception;

import com.company.servicebase.exception.BizCodeEnume;
import com.company.servicebase.exception.MyException;
import com.company.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestControllerAdvice(basePackages = "com.company.eduorder.controller")
public class ExceptionControllerAdvice {

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleVaildException (MethodArgumentNotValidException e) {
        log.error("数据校验出现问题{}, 异常类型，{}", e.getMessage(), e.getClass());
        Map<String, String> errorsMap = new HashMap<>(10);

        BindingResult bindingResult = e.getBindingResult();
        bindingResult.getFieldErrors().forEach((error) -> {
            errorsMap.put(error.getField(), error.getDefaultMessage());
        });

        return R.error().code(BizCodeEnume.VAILD_EXCEPTION.getCode()).message(BizCodeEnume.VAILD_EXCEPTION.getMsg()).data("data", errorsMap);
    }

    @ExceptionHandler(value = Throwable.class)
    public R handleVaildException (Throwable e) {
        log.error("系统未知错误", e);
        return R.error().code(BizCodeEnume.UNKNOW_EXCEPTION.getCode()).message(BizCodeEnume.UNKNOW_EXCEPTION.getMsg());
    }

    //自定义异常
    @ExceptionHandler(MyException.class)
    @ResponseBody //为了返回数据
    public R error(MyException e) {
        log.error(e.getMessage());
        e.printStackTrace();
        return R.error().code(e.getCode()).message(e.getMsg());
    }

}
